define(['app', 'clipboard', 'sql-formatter'], function(app, Clipboard, sqlFormatter) {
    app.controller('SqlMatcherController', function($scope) {
        var self = this;
        self.preparedSql = '';
        self.parameters = '';
        self.code = '';

        const quotTypes = ['String', 'Date', 'Timestamp'];
        var sqlViewer = null;

        self.init = function() {
            self.preparedSql = 'SELECT password, enabled FROM users WHERE name = ? OR email = ?';
            self.parameters = 'admin(String), admin@qq.com(String)';

            new Clipboard('#copy', {
                text: function() {
                    return self.code;
                }
            });

            // sql viewer
            sqlViewer = ace.edit('sql-viewer');
            sqlViewer.getSession().setMode("ace/mode/mysql");
            sqlViewer.setOptions({
                fontSize: 12,
                //wrap: true,
                readOnly: true,
                showGutter: false,
                showLineNumbers: false,
                showPrintMargin: false,
                highlightActiveLine: false,
                autoScrollEditorIntoView: true
            });

            $scope.$watch('vm.code', function(newValue) {
                sqlViewer.setValue(newValue, -1);
                sqlViewer.resize();
            });
        }

        self.reset = function() {
            self.preparedSql = '';
            self.parameters = '';
            self.code = '';
        }

        self.match = function(valid) {
            if (valid) {
                var parameters = [];
                angular.forEach(self.parameters.split(','), function(parameter) {
                    parameter = parameter.trim();
                    var value = parameter.replace(/\(.*\)/, '');
                    var type = parameter.replace(/\(|\)/g, '').substring(value.length);
                    if (quotTypes.indexOf(type) >= 0) {
                        value = '\'' + value + '\'';
                    }
                    parameters.push(value);
                });

                var index = 0;
                self.code = sqlFormatter.format(self.preparedSql, {
                    indent: '    ',
                    language: 'sql',
                    params: parameters
                });
            }
        }
    });
});
